using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.UI.YGUI;

namespace com.yoozoo.gta
{
    /// <summary>
    /// YScrollViewFollower is used to follow the scroll position of YScrollRect.
    /// </summary>
    public class YScrollViewFollower : MonoBehaviour
    {
        /// <summary>
        /// Direction of the scroll.
        /// </summary>
        public enum Direction
        {
            Vertical,
            Horizontal
        }
        
        public YScrollRect m_ScrollRect;
        public Direction m_Direction = Direction.Vertical;

        void Awake()
        {
            if (m_ScrollRect != null)
            {
                m_ScrollRect.onValueChanged.AddListener(OnScrollValueChanged);
            }
        }

        void OnDestroy()
        {
            if (m_ScrollRect != null)
            {
                m_ScrollRect.onValueChanged.RemoveListener(OnScrollValueChanged);
            }
        }

        /// <summary>
        /// OnScrollValueChanged is called when the scroll position of YScrollRect is changed.
        /// 2024年8月10日这个地方如果视口的宽或高大于自己的宽或高会有问题 @黄睿
        /// </summary>
        /// <param name="pos">scroll percent of yscrollrect</param>
        private void OnScrollValueChanged(Vector2 pos)
        {
            var rectTransform = gameObject.GetComponent<RectTransform>();
            
            // Set the position of the follower.
            if (m_Direction == Direction.Horizontal)
            {
                var width = rectTransform.rect.width - m_ScrollRect.viewport.rect.width;
                var posY = rectTransform.anchoredPosition.y;
                var posX = width * pos.x;
                rectTransform.anchoredPosition = new Vector2(posX, posY);
            }
            else
            {
                var height = rectTransform.rect.height - m_ScrollRect.viewport.rect.height;
                var posX = rectTransform.anchoredPosition.x;
                var posY = height * pos.y;
                rectTransform.anchoredPosition = new Vector2(posX, posY);
            }
        }
    }
}
